<?php

namespace Hellophp;

class Db {

    private $_dbh;

    public function __construct($instanceName = 'default') {

        $option = Config::get('db.'.$instanceName);
        $attr = array(
            \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
            \PDO::ATTR_STRINGIFY_FETCHES => false,
            \PDO::ATTR_EMULATE_PREPARES => false,
        );
        try {
            $this->_dbh = new \PDO($option['dsn'], $option['user'], $option['password'], $attr);
            if (!empty($option['charset'])) {
                $this->_dbh->exec('SET NAMES '.$option['charset']);
            }
            Logger::log(sprintf('connect to %s succeed.', $option['dsn']));
        } catch (\PDOException $e) {
            Logger::log(sprintf('connect to %s failed.', $option['dsn']));
            throw new Db\Exception('Connect to db('.$option['dsn'].') failed: ' . $e->getMessage(), Db\Exception::DB_CONNECT_FAILED);
        }
    }

    public function query($query, $params = []) {

        try {
            $stmt = $this->_dbh->prepare($query);
            $stmt->execute($params);
            $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            Logger::log(sprintf('db query: %s (%s) => %s', $query, json_encode($params), json_encode($rows)));
            return $rows;
        } catch (\PDOException $e) {
            Logger::log(sprintf('db query failed. query=%s, params=%s', $query, json_encode($params)));
            throw new Db\Exception('db query failed: ' . $e->getMessage(), Db\Exception::DB_QUERY_FAILED);
        }
    }
}